package com.dqhl.community.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.UserSaveUtil;
import com.dqhl.community.view.CircleImageView;
import com.dqhl.community.view.ConfirmDialog;

import org.xutils.x;

/**
 * Created by cheng on 2016/8/29.
 * 个人设置 acctivity
 */
public class PersonalSettingActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private CircleImageView ivHeadPortrait; //头像控件
    private TextView tvNickname; //用户昵称
    private String photoPath; // 头像的路径
    private TextView tvCommunity; //用户小区名字
    private TextView tv_phone; //用户手机号


    private LinearLayout llPersonalInfo; // 包含头像昵称的个人信息
    private LinearLayout llUpdateCommunity; // 完善小区资料
    private LinearLayout llModifyPhone; // 修改绑定手机
    private LinearLayout llModifyPassword; // 修改密码
    private Button btnLogout;

    private String strUserId;
    private String strNickname;
    private String strUserPhone;
    private String authentication;
    private ImageView iv_binding_weixin;
    private ImageView iv_binding_qq;
    private String wxstate;
    private String qqstate;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_setting);
        registerBroadcastReceiver();
        initView();
        loadData();
    }

    /**
     * 初始化数据
     */
    private void loadData() {
        wxstate = spUserInfo.getString(Constant.WXSTATE, "");
        qqstate = spUserInfo.getString(Constant.QQSTATE, "");
        strUserId = spUserInfo.getString(Constant.USERID, "");
        strNickname = spUserInfo.getString(Constant.NICKNAME, "");
//        strUserPhone = spUserInfo.getString(Constant.USER_PHONE, "");
        strUserPhone = user.getPhone();
        authentication = spUserInfo.getString(Constant.AUTHENTICATION, "");
        // 从SharedPreferences获取头像的路径
        photoPath = spUserInfo.getString(Constant.PHOTO_PATH, "");
        Dlog.e("SharedPreferences里头像路径：" + photoPath);

        if (photoPath != null && photoPath.length() > 0) {
            x.image().bind(ivHeadPortrait, Config.Api.base_img_url + photoPath);
        } else {
            // 显示一张默认的头像
            ivHeadPortrait.setImageResource(R.drawable.ic_no_head_portrait);
        }
        if (strNickname != null && strNickname.length() > 0) {
            tvNickname.setText(strNickname);
        } else {
            tvNickname.setText("修改资料");
        }
        if (!"".equals(authentication) && authentication.length() > 0) {
            tvCommunity.setText(spUserInfo.getString(Constant.COMMUNITY_ID, "去认证"));
        } else {
            tvCommunity.setText("未认证");
        }
        if (!"".equals(strUserPhone) && strUserPhone.length() > 0) {
            String tvPhone = strUserPhone.substring(0, 3) + "****"
                    + strUserPhone.substring(7, strUserPhone.length());
            tv_phone.setText(tvPhone);
        }
        if ("2".equals(wxstate)) {
            iv_binding_weixin.setImageResource(R.drawable.ic_setting_weixin);
        } else {
            iv_binding_weixin.setImageResource(R.drawable.ic_setting_weixin2);
        }
        if ("2".equals(qqstate)) {
            iv_binding_qq.setImageResource(R.drawable.ic_setting_qq);
        } else {
            iv_binding_qq.setImageResource(R.drawable.ic_setting_qq2);
        }
    }

    /**
     * 定义 BroadcastReceiver
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.ACTION_PHOTO_MODIFY: // 更新头像
                    x.image().bind(ivHeadPortrait, intent.getStringExtra(Constant.PHOTO_PATH));
                    break;
                case Constant.ACTION_COMPLAIN: //认证成功
                    tvCommunity.setText(intent.getStringExtra(Constant.COMMUNITY_NAME));
                    break;
                case Constant.ACTION_UPDATA_SUCCESS://修改昵称
                    tvNickname.setText(intent.getStringExtra(Constant.NICKNAME));
                    break;
                case Constant.ACTION_MODIFY_PHONE_SUCCESS: //修改手机号
                    String phone = intent.getStringExtra(Constant.USER_PHONE);
                    String tvPhone = phone.substring(0, 3) + "****"
                            + phone.substring(7, phone.length());
                    tv_phone.setText(tvPhone);
                    break;

            }
        }
    };

    /**
     * 注册广播
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_PHOTO_MODIFY); //更换头像
        intentFilter.addAction(Constant.ACTION_COMPLAIN); //认证
        intentFilter.addAction(Constant.ACTION_UPDATA_SUCCESS);//修改昵称
        intentFilter.addAction(Constant.ACTION_MODIFY_PHONE_SUCCESS);//修改手机号
        registerReceiver(receiver, intentFilter);
    }

    private void initView() {
        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopTitle.setText(R.string.txt_personal_setting);

        ivHeadPortrait = (CircleImageView) findViewById(R.id.iv_head_portrait);
        tvNickname = (TextView) findViewById(R.id.tv_nickname);
        tvCommunity = (TextView) findViewById(R.id.tv_community);
        llPersonalInfo = (LinearLayout) findViewById(R.id.ll_personal_info);
        llUpdateCommunity = (LinearLayout) findViewById(R.id.ll_update_community);
        llModifyPhone = (LinearLayout) findViewById(R.id.ll_modify_phone);
        llModifyPassword = (LinearLayout) findViewById(R.id.ll_modify_password);
        btnLogout = (Button) findViewById(R.id.btn_logout);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        iv_binding_weixin = (ImageView) findViewById(R.id.iv_binding_weixin);
        iv_binding_qq = (ImageView) findViewById(R.id.iv_binding_qq);

        ivTopBack.setOnClickListener(this);
        llPersonalInfo.setOnClickListener(this);
        llUpdateCommunity.setOnClickListener(this);
        llModifyPhone.setOnClickListener(this);
        llModifyPassword.setOnClickListener(this);
        btnLogout.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.ll_personal_info: //跳至修改个人信息界面
                overlay(PersonalInfoActivity.class);
                break;
            case R.id.ll_update_community:  // 完善小区资料
                Bundle bundle = new Bundle();
                bundle.putString("user_id", app.getUserId());
                Dlog.e("从个人设置认证传递的userid：" + app.getUserId());
                overlay(LocationCommunityActivity.class, bundle);
                break;
            case R.id.ll_modify_phone:  // 修改绑定手机
                overlay(ModifyPhoneActivity.class);
                break;
            case R.id.ll_modify_password:  // 修改密码
                overlay(ModifyPwdActivity.class);
                break;
            case R.id.btn_logout:  // 退出登录
                showLogoutDialog();
                break;
            default:
                break;
        }
    }

    /**
     * 显示确认退出dialog
     */
    private void showLogoutDialog() {
        final ConfirmDialog confirmDialog = new ConfirmDialog(PersonalSettingActivity.this,
                "确定退出帐号？", "确定", "取消");
        confirmDialog.setButtonClickListener(new ConfirmDialog.ButtonClickListener() {
            @Override
            public void doConfirm() {
                confirmDialog.dismiss();
                doLogout();
            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
        confirmDialog.show();
    }

    /**
     * 清除帐号信息，退出登录
     */
    private void doLogout() {
        UserSaveUtil.saveUser(this, null);

        //将user信息从application中清除
        app.setUserId("");
        app.setAuthentication("");

        //将user信息从SharedPreferences中清除
        spUserInfo.edit().clear().apply();
        sendLogoutBroadCast();
        finish();
    }

    /**
     * 发送一个退出登录的广播
     */
    private void sendLogoutBroadCast() {
        Intent intent = new Intent(Constant.ACTION_LOGOUT);
        sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

}
